﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LuckyFish.Ledger.Data;
using Microsoft.EntityFrameworkCore.Internal;

namespace LuckyFish.Ledger.App.Views;

public partial class AddLedgerView : Window
{
    public AddLedgerView()
    {
        InitializeComponent();
#if DEBUG
        this.AttachDevTools();
#endif
        NameBox = this.FindControl<TextBox>("NameBox");
        AmountBox = this.FindControl<TextBox>("AmountBox");
        CategoryComboBox = this.FindControl<ComboBox>("CategoryComboBox");
        using var context = new LedgerContext();
        CategoryComboBox.Items = context.Categorys.ToArray();
        if (!context.Categorys.Any())
        {
            var a = new List<CategoryModel>
            {
                new (){CategoryName = "Food",Explanation = "eat"},
                new (){CategoryName = "Shopping",Explanation = "shopping"},
                new (){CategoryName = "Playing",Explanation = "play"}
            };
            CategoryComboBox.Items = a;
            a.ForEach(x => context.Categorys.Add(x));
        }
        context.SaveChanges();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void Ok(object? sender, RoutedEventArgs e)
    {
        Close(new LedgerModel(NameBox.Text, decimal.Parse(AmountBox.Text),
            (CategoryComboBox.SelectedItem as CategoryModel).CategoryName, DateTime.Today.ToString(CultureInfo.InvariantCulture)));
    }

    private void Cancel(object? sender, RoutedEventArgs e)
    {
        Close(null);
    }
}